package com.huika.dealontop.control.nearby.activity;

import android.content.Context;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.base.BaseAda;
import com.huika.dealontop.support.domain.OrderDetailBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.views.ListViewForScrollView;
import com.huika.dealontop.views.TitleBarHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

/**
 * @author chenyuan
 * @description：退款页面
 * @date 2015年11月16日 上午11:25:04
 */
public class RefundApplyActivity extends BaseAct {

    public static String REFUND_ARRAY = "refund_array";
    public static String REFUND_ORDERID = "refund_orderId";

    private ListViewForScrollView select_bonus_code_lv;
    private ListViewForScrollView select_reason_lv;
    private SelectBonusAdapter adapter;
    private SelectReasonAdapter reasonAdapter;
    private Button btn_confirm_submit;
    private ArrayList<OrderDetailBean.DataBean> datas;
    private String orderId;
    private EditText refund_resson_et;
    private TextView refund_resson_num_tv;
    private int type = 0;
    private OrderDetailBean mOrderDetailBean;

    @Override
    protected void initData() {
        super.initData();
        orderId = getIntent().getStringExtra(REFUND_ORDERID);
//        datas = (ArrayList<OrderDetailBean.DataBean>) getIntent().getSerializableExtra(REFUND_ARRAY);

    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_refund_apply);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        new TitleBarHelper(this, R.string.common_empty, R.string.common_empty, R.string.refund_apply_title);
        select_bonus_code_lv = (ListViewForScrollView) findViewById(R.id.select_bonus_code_lv);
        select_reason_lv = (ListViewForScrollView) findViewById(R.id.select_reason_lv);
        btn_confirm_submit = (Button) findViewById(R.id.btn_confirm_submit);
        refund_resson_num_tv = (TextView) findViewById(R.id.refund_resson_num_tv);
        refund_resson_et = (EditText) findViewById(R.id.refund_resson_et);
        btn_confirm_submit.setOnClickListener(this);
        adapter = new SelectBonusAdapter(this);
        select_bonus_code_lv.setAdapter(adapter);
//        adapter.setGroup(setData());


        reasonAdapter = new SelectReasonAdapter(this);
        select_reason_lv.setAdapter(reasonAdapter);
        reasonAdapter.setGroup(setReasonData());

        refund_resson_et.addTextChangedListener(new MyTextChanged());


        select_reason_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int relPosition = position - select_reason_lv.getHeaderViewsCount();
                if (relPosition >= 0 && relPosition < reasonAdapter.getCount()) {
                    type = relPosition + 1;
                    reasonAdapter.relPos = relPosition;
                    reasonAdapter.notifyDataSetChanged();
                }
            }
        });

        startLoadData();

    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        if (v.getId() == R.id.btn_confirm_submit) {

            if (TextUtils.isEmpty(getTicketStr(adapter.ticketSet))) {
                showToastMsg(getString(R.string.refund_apply_select_coupon));
                return;
            }
            if (type == 0) {
                showToastMsg(getString(R.string.refund_apply_select_reasons));
                return;
            }
//            else{
//                if (reasonAdapter.refundCauseSet.size()>1){
//                    showToastMsg(getString(R.string.refund_apply_select_reason_des));
//                    return;
//                }
//            }

//            if (TextUtils.isEmpty(getInputStr(refund_resson_et))){
//                showToastMsg(getString(R.string.refund_apply_input_refund_des));
//                return;
//            }

            getMemberReimburseData();
        }
    }

    private ArrayList<HashMap<String, String>> setData() {
        ArrayList<HashMap<String, String>> datas = new ArrayList<HashMap<String, String>>();
        for (int i = 2; i < 7; i++) {
            HashMap<String, String> bean = new HashMap<String, String>();
            bean.put("couponCode", "35030319900812075" + i);
            bean.put("couponStatus", i + "");
            bean.put("ticketID", i + "");
            datas.add(bean);
        }
        return datas;
    }

    private ArrayList<String> setReasonData() {
        ArrayList<String> datas = new ArrayList<String>();
        datas.add(getString(R.string.refund_apply_refuse_reason1));
        datas.add(getString(R.string.refund_apply_refuse_reason2));
        datas.add(getString(R.string.refund_apply_refuse_reason3));
        datas.add(getString(R.string.refund_apply_refuse_reason4));
        datas.add(getString(R.string.refund_apply_refuse_reason5));
        datas.add(getString(R.string.refund_apply_refuse_reason8));
        datas.add(getString(R.string.refund_apply_refuse_reason6));
        datas.add(getString(R.string.refund_apply_refuse_reason7));

        return datas;
    }


    /**
     * 原因选择适配器
     */
    private class SelectReasonAdapter extends BaseAda<String> {


        private int relPos = -1;

        public SelectReasonAdapter(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder vh = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_refund_reason, parent, false);
                vh = new ViewHolder(convertView);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }

            vh.rb_reason_tv.setText("" + getItem(position));
            vh.reason_cb.setImageResource(position == relPos ? R.mipmap.common_select_choise_icon : R.mipmap.common_unselect_choise_icon);
            return convertView;
        }

        class ViewHolder {
            public TextView rb_reason_tv;
            public ImageView reason_cb;

            public ViewHolder(View convertView) {
                rb_reason_tv = (TextView) convertView.findViewById(R.id.rb_reason_tv);
                reason_cb = (ImageView) convertView.findViewById(R.id.reason_cb);
            }
        }


    }


    /**
     * 优惠券选择适配器
     */
    private class SelectBonusAdapter extends BaseAda<OrderDetailBean.DataBean> {

        private int flag;

        public HashSet<String> ticketSet = new HashSet<String>();
        public HashMap<Integer,View> noUseMap = new HashMap<Integer,View>();

        public SelectBonusAdapter(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder vh = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_use_bonus_code, parent, false);
                vh = new ViewHolder(convertView);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }

            vh.rb_price_tv.setText(setCodeFormat(getItem(position).getCouponCode()));

            switch (getItem(position).getCouponStatus()) {//couponStatus:团购码状态  2未使用，3已使用，4：退款中，5：已退款，6已过期（可退款,扣订单支付金额20%，可消费)
                case 2:
                    vh.modify_tv.setText(getString(R.string.myorder_list_filter_nouse));
                    vh.num_cb.setBackgroundResource(R.drawable.selector_use_coupon_bg);
                    flag = 2;
                    noUseMap.put(flag,convertView);
//                    convertView.setClickable(true);
                    break;
                case 3:
                    vh.modify_tv.setText(getString(R.string.myorder_list_has_use));
                    vh.num_cb.setBackgroundResource(R.mipmap.common_unselect_has_choise_icon);
                    flag = 3;
                    noUseMap.put(flag,convertView);
//                    convertView.setClickable(false);
                    break;
                case 4:
                    vh.modify_tv.setText(getString(R.string.myorder_list_refuning));
                    vh.num_cb.setBackgroundResource(R.mipmap.common_unselect_has_choise_icon);
                    flag = 4;
                    noUseMap.put(flag,convertView);
//                    convertView.setClickable(false);
                    break;
                case 5:
                    vh.modify_tv.setText(getString(R.string.myorder_list_has_refund));
                    vh.num_cb.setBackgroundResource(R.mipmap.common_unselect_has_choise_icon);
                    flag = 5;
                    noUseMap.put(flag,convertView);
//                    convertView.setClickable(false);
                    break;
                case 6:
                    vh.modify_tv.setText(getString(R.string.myorder_list_has_expired));
                    vh.num_cb.setBackgroundResource(R.mipmap.common_unselect_has_choise_icon);
                    flag = 6;
                    noUseMap.put(flag,convertView);
//                    convertView.setClickable(false);
                    break;
            }



            convertView.setOnClickListener(new MyClickListener(vh, position));
            return convertView;
        }

        class ViewHolder {
            public CheckBox num_cb;
            public TextView modify_tv;
            public TextView rb_price_tv;

            public ViewHolder(View convertView) {
                num_cb = (CheckBox) convertView.findViewById(R.id.num_cb);
                modify_tv = (TextView) convertView.findViewById(R.id.modify_tv);
                rb_price_tv = (TextView) convertView.findViewById(R.id.rb_price_tv);
            }
        }

        class MyClickListener implements View.OnClickListener {
            ViewHolder vh;
            int posit;

            public MyClickListener(ViewHolder viewHolder, int position) {
                vh = viewHolder;
                posit = position;
            }

            @Override
            public void onClick(View v) {
                if (vh.num_cb.isChecked()) {
                    vh.num_cb.setChecked(false);
                    for (Integer pos:noUseMap.keySet()){
                        if (pos==2){
                            ticketSet.remove(getItem(posit).getTicketId());
                            Log.d("cy", "ticketSet:" + ticketSet);
                        }
                    }

                } else {
                    vh.num_cb.setChecked(true);
                    for (Integer pos:noUseMap.keySet()){
                        if (pos==2){
                            ticketSet.add(getItem(posit).getTicketId());
                            Log.d("cy", "ticketSet:" + ticketSet);
                        }
                    }
                }
            }
        }


    }

    private String getTicketStr(HashSet<String> set) {
        StringBuilder sb = new StringBuilder();
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                sb.append(iterator.next()).append(",");
                Log.d("cy", "ticketStr:" + sb.toString().substring(0, sb.toString().length() - 1));

            }
            if (!sb.toString().isEmpty())
                return sb.toString().substring(0, sb.toString().length() - 1);
        }

        return "";
    }

    private String getrefundCause(HashSet<String> set) {
        String str = null;
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                str = (String) iterator.next();
            }
        }
        return str;
    }


    private void getMemberReimburseData() {

        showLoadingDialog(getString(R.string.common_loading));
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        getUserId(ajaxParams);
        ajaxParams.putCommonTypeParam("orderID", orderId);//订单ID(RSA加密)
        ajaxParams.putCommonTypeParam("refundCause", getInputStr(refund_resson_et));//退款原因

        ajaxParams.putCommonTypeParam("ticketStr", getTicketStr(adapter.ticketSet));//券ID(多个券ID 使用逗号隔开)
        ajaxParams.putCommonTypeParam("refundType", "" + type);//退款类型（1.预约不上 2.商家营业但不接待 3.商家停业/装修/转让 4.买多了/买错了 5.去过了，非常不满意 6.计划有变，没时间消费 7.后悔了，不想要了 8.商家说可以直接以团购价到店消费）

        FormResultRequest<HashMap<String, String>> getResultRequest = new FormResultRequest<HashMap<String, String>>(
                UrlConstants.MEMBERREIMBURSE, memberReimburseReq, this,
                new TypeToken<RequestResult<HashMap<String, String>>>() {
                }.getType());
        getResultRequest.setRequestParams(ajaxParams);
        executeRequest(getResultRequest);

    }

    private void getUserId(JSONWrapAjaxParams ajaxParams) {
        long u_id = GlobalApp.getInstance().getUserId();
        ajaxParams.putCommonTypeParam("userID", u_id);
    }

    private Response.Listener<RequestResult<HashMap<String, String>>> memberReimburseReq = new Response.Listener<RequestResult<HashMap<String, String>>>() {

        @Override
        public void onResponse(RequestResult<HashMap<String, String>> result) {
            if (result.flag == 1) {
                showToastMsg(getString(R.string.refund_reason_success_des));
                finish();
            }else{
                showToastMsg(getString(R.string.refund_reason_fail_des));
            }

            dismissLoadingDialog();

        }
    };

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
        super.onErrorResponse(error);
        dismissLoadingDialog();
    }

    private class MyTextChanged implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            refund_resson_et.setSelection(s.toString().length());
            int max = 400;
            if (getInputStr(refund_resson_et).length() > max) {
                refund_resson_num_tv.setText(Html.fromHtml("<font color=#f73a3a>" + (max - getInputStr(refund_resson_et).length()) + "</font>/" + max));
                refund_resson_et.setText(getInputStr(refund_resson_et).subSequence(0, max));
            } else {
                refund_resson_num_tv.setText(Html.fromHtml("" + (max - getInputStr(refund_resson_et).length()) + "/" + max));
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
//            refund_resson_et.setSelection(s.toString().length());
        }

    }

    private void startLoadData() {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", GlobalApp.getInstance().getUserId());
        ajaxParams.putCommonTypeParam("orderID", orderId);
        FormResultRequest<ArrayList<OrderDetailBean>> loginRequest = new FormResultRequest(UrlConstants.ORDER_DETAIL, getOrderDetailReq, this,
                new TypeToken<RequestResult<ArrayList<OrderDetailBean>>>() {
                }.getType());
        loginRequest.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(loginRequest);
    }

    private Response.Listener<RequestResult<ArrayList<OrderDetailBean>>> getOrderDetailReq = new Response.Listener<RequestResult<ArrayList<OrderDetailBean>>>() {

        @Override
        public void onResponse(RequestResult<ArrayList<OrderDetailBean>> result) {
            dismissLoadingDialog();
            if (result.getRs() != null && result.getRs().size() > 0) {
                mOrderDetailBean = result.getRs().get(0);
                datas=mOrderDetailBean.getData();
                adapter.setGroup(datas);
                Log.d("cy", "datas" + datas);
            }
        }
    };

    private String setCodeFormat(String str){
        StringBuilder formatStr=new StringBuilder();
        if (str!=null&&!str.isEmpty()){
            if (str.length()==13){
                formatStr.append(str.substring(0,5)).append(" ").append(str.substring(5,9)).append(" ").append(str.substring(9,str.length()));
            }else{
                formatStr.append(str.substring(0,4)).append(" ").append(str.substring(4,8)).append(" ").append(str.substring(8,str.length()));
            }
        }

        return formatStr.toString();
    }


}


